<template>
  <div class="app-container">
    <div class="query-box">
      <el-row :gutter="24">
        <el-col :span="4" :xs="24">
          <el-button type="primary" plain icon="el-icon-circle-plus-outline" size="small" class="mr10"
                     @click="handleAdd()">新增
          </el-button>
        </el-col>
        <el-col :span="20" :xs="24" align="right">
          <el-form :model="query" ref="queryForm" :inline="true" label-width="70px">
            <el-form-item label="编码：">
              <el-input
                v-model="query.code"
                clearable
                size="small"
              />
            </el-form-item>
            <el-form-item label="名称：">
              <el-input
                v-model="query.name"
                clearable
                size="small"
              />
            </el-form-item>
            <el-button type="primary" icon="el-icon-search" size="small" @click="handleSearch">搜索</el-button>
          </el-form>
        </el-col>
      </el-row>
    </div>

    <el-table v-loading="loading" :data="list" element-loading-text="Loading" border fit class="table">
      <el-table-column label="项目设置" align="center">
          <el-table-column align="center" label="编码" prop="code"></el-table-column>
          <el-table-column align="center" label="名称" prop="name"></el-table-column>
          <el-table-column align="center" label="端口" prop="port" width="70"></el-table-column>
          <el-table-column align="center" label="包路径" prop="packagePath"></el-table-column>
          <el-table-column align="center" label="日志文件地址" prop="logPath"></el-table-column>
          <el-table-column align="center" label="来源类型" prop="sourceType">
            <template slot-scope="scope">
              <span>{{ sourceType[scope.row.sourceType]}}</span>
            </template>
          </el-table-column>
      </el-table-column>
      <el-table-column label="数据库设置" align="center">
        <el-table-column align="center" label="主机" prop="dbHost"></el-table-column>
        <el-table-column align="center" label="端口" prop="dbPort" width="70"></el-table-column>
        <el-table-column align="center" label="数据库" prop="dbName"></el-table-column>
        <el-table-column align="center" label="DB类型" prop="sourceType">
          <template slot-scope="scope">
            <span>{{ sourceType[scope.row.sourceType]}}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="Redis设置" align="center">
        <el-table-column align="center" label="Redis" prop="redisEnable">
          <template slot-scope="scope">
            <span>{{ userStatus[scope.row.redisEnable]}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="主机" prop="redisHost"></el-table-column>
        <el-table-column align="center" label="端口" prop="redisPort" width="70"></el-table-column>
        <el-table-column align="center" label="库" prop="redisDb" width="50"></el-table-column>
      </el-table-column>
      <el-table-column label="其他设置" align="center">
        <el-table-column align="center" label="Swagger" prop="swaggerEnable" width="75">
          <template slot-scope="scope">
            <span>{{ userStatus[scope.row.swaggerEnable]}}</span>
          </template>
        </el-table-column>
      </el-table-column>

      <el-table-column align="center" label="下载" prop="downloadUrl" width="80">
        <template slot-scope="scope">
          <a href="#" @click="openDoenload(scope.row)" v-if="scope.row.downloadUrl">
          <i class="iconfont el-icon-download list-icon-green"/>
          </a>
          <i class="iconfont el-icon-remove-outline list-icon-gray" v-else/>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="createTime" label="添加时间" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime | datetimeFormat}}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="190"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            :disabled="isGenBtnDisabled"
            @click="genProject(scope.$index, scope.row)"
          >{{genBtnText}}
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="showDetail(scope.row)"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleAdd(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDel(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination background layout="total, prev, pager, next" :current-page="query.pageNo"
                     :page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
    </div>

    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-progress
          :text-inside="true"
          :stroke-width="20"
          :percentage="progress.percent"
          :status="progress.progressStatus"
          style="padding-bottom: 20px;"
        >
        </el-progress>
        <el-row v-if="progress.step == 0">
          <el-col :span="24">
            <el-form-item label="项目名称" prop="name">
              <el-input v-model="form.name"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目编码" prop="code">
              <el-input v-model="form.code"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务端口" prop="port">
              <el-input v-model="form.port" oninput="value=value.replace(/[^\d.]/g,'')"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="包路径" prop="packagePath">
              <el-input v-model="form.packagePath"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="日志地址" prop="logPath">
              <el-input v-model="form.logPath"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="项目描述" prop="description">
              <el-input type="textarea" :rows="5" v-model="form.description"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="progress.step == 1">
          <el-col :span="24">
            <el-form-item label="主机" prop="dbHost">
              <el-input v-model="form.dbHost"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="端口" prop="dbPort">
              <el-input v-model="form.dbPort" oninput="value=value.replace(/[^\d.]/g,'')"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="数据库" prop="dbName">
              <el-input v-model="form.dbName"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="用户名" prop="dbUsername">
              <el-input v-model="form.dbUsername"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="dbPassword">
              <el-input v-model="form.dbPassword" type="password"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="padding-left: 15px">
            <el-button type="success" @click="testDb" size="medium" :disabled="isTestDbBtnDisabled" plain>测试连接</el-button>
          </el-col>
        </el-row>
        <el-row v-if="progress.step == 2">
          <el-col :span="24">
            <el-form-item label="来源类型" prop="sourceType">
            <el-radio-group v-model="form.sourceType">
              <el-radio v-for="item in Object.keys(sourceType)" :label="item" :value="item">{{sourceType[item]}}</el-radio>
            </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.sourceType==1">
            <p style="line-height: 30px;text-indent: 2rem;">您选择的根据数据库生成项目，则对象的实体类会从您上一步配置的数据库的表自动生成。因此需要<span class="font-red-bolder">上一步数据库的配置能够被此服务正常访问</span>。即确保上一步的<span class="font-red-bolder">测试连接能正常通过</span>。否则将无法正常生成项目。</p>
          </el-col>
          <el-col :span="24" v-if="form.sourceType==3">
            <el-form-item label="SQL语句" prop="sqlStatement">
              <el-input type="textarea" :rows="15" v-model="form.sqlStatement"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="progress.step == 3">
          <el-col :span="24">
            <el-form-item label="Redis" prop="redisEnable">
              <el-radio-group v-model="form.redisEnable">
                <el-radio v-for="item in Object.keys(userStatus)" :label="item" :value="item">{{userStatus[item]}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.redisEnable==1">
            <el-form-item label="主机" prop="redisHost" :rules="form.redisEnable === 1 ?rules.redisHost:[{ required: false}]">
              <el-input v-model="form.redisHost"/>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.redisEnable==1">
            <el-form-item label="端口" prop="redisPort">
              <el-input v-model="form.redisPort" oninput="value=value.replace(/[^\d.]/g,'')"/>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.redisEnable==1">
            <el-form-item label="连接库" prop="redisDb">
              <el-input v-model="form.redisDb"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.redisEnable==1">
            <el-form-item label="密码" prop="redisPassword">
              <el-input v-model="form.redisPassword" type="password"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="padding-left: 15px" v-if="form.redisEnable==1">
            <el-button type="success" @click="testRedis" size="medium" :disabled="isTestRedisBtnDisabled" plain>测试连接</el-button>
          </el-col>
        </el-row>
        <el-row v-if="progress.step == 4">
          <el-col :span="24">
            <el-form-item label="Swagger" prop="swaggerEnable" label-width="100px">
              <el-radio-group v-model="form.swaggerEnable">
                <el-radio v-for="item in Object.keys(userStatus)" :label="item" :value="item">{{userStatus[item]}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="progress.step == 5">
          <el-col :span="24" align="center">
            <span>恭喜您，请点击下面的生成按钮生成吧</span>
            <p>
            <i class="iconfont el-icon-thumb list-icon-blue" style="font-size: 7rem;cursor:pointer;" :disabled="isSaveBtnDisabled" @click="submitForm"/>
            </p>
          </el-col>
        </el-row>
        <el-row v-if="progress.step == 6">
          <el-col :span="24" align="center" v-if="genResult">
            <i class="iconfont el-icon-success list-icon-green" style="text-align: center; font-size: 7rem;"/>
            <p>生成项目成功，<a :href="genDownloadUrl" target="_blank" class="font-red-bolder">点我下载</a>&ensp;或复制下面链接下载：</p>
            <p>{{genDownloadUrl}}</p>
          </el-col>
          <el-col :span="24" align="center" v-else>
            <i class="iconfont el-icon-error list-icon-red" style="text-align: center; font-size: 7rem;"/>
            <p>生成项目失败，失败原因：</p>
            <p>{{genResultErr}}</p>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="nextStep" v-if="progress.step < 6">下一步</el-button>
        <el-button type="primary" @click="lastStep" v-if="progress.step > 0">上一步</el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="detail.title" :visible.sync="detail.open" width="500px" append-to-body>
      <el-form ref="form" label-width="90px">
        <el-row>
          <el-tabs v-model="projectItemTab">
            <el-tab-pane label="项目信息" name="PROJECT">
                <el-col :span="24">
                  <el-form-item label="项目名称：" prop="name" style="margin-bottom:0;">{{form.name}}</el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="项目编码：" prop="code" style="margin-bottom:0;">{{form.code}}</el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="服务端口：" prop="port" style="margin-bottom:0;">{{form.port}}</el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="包路径：" prop="packagePath" style="margin-bottom:0;">{{form.packagePath}}</el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="日志地址：" prop="logPath" style="margin-bottom:0;">{{form.logPath}}</el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="项目描述：" prop="description" style="margin-bottom:0;">{{form.description}}</el-form-item>
                </el-col>
            </el-tab-pane>
            <el-tab-pane label="数据库" name="DB" :key="2">
              <el-col :span="24">
                <el-form-item label="主机：" prop="dbHost" style="margin-bottom:0;">{{form.dbHost}}</el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="端口：" prop="dbPort" style="margin-bottom:0;">{{form.dbPort}}</el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="用户名：" prop="dbUsername" style="margin-bottom:0;">{{form.dbUsername}}</el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="数据库：" prop="dbName" style="margin-bottom:0;">{{form.dbName}}</el-form-item>
              </el-col>
            </el-tab-pane>
            <el-tab-pane label="来源类型" name="sourceType" :key="2">
              <el-col :span="24">
                <el-form-item label="来源类型：" prop="sourceType" style="margin-bottom:0;">{{sourceType[form.sourceType]}}
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <p style="line-height: 30px;text-indent: 2rem;" v-if="form.sourceType==1">您选择的根据数据库生成项目，则对象的实体类会从您上一步配置的数据库的表自动生成。因此需要<span class="font-red-bolder">上一步数据库的配置能够被此服务正常访问</span>。即确保上一步的<span class="font-red-bolder">测试连接能正常通过</span>。否则将无法正常生成项目。</p>
                <el-form-item label="SQL语句" style="margin-bottom:0;" v-if="form.sourceType==3">
                  <el-input type="textarea" :rows="9" v-model="form.sqlStatement"/>
                </el-form-item>
              </el-col>
            </el-tab-pane>
            <el-tab-pane label="Redis" name="REDIS" :key="3">
              <el-col :span="24">
                <el-form-item label="Redis：" prop="redisEnable" style="margin-bottom:0;">
                  <span v-if="form.redisEnable == 1">使用</span>
                  <span v-if="form.redisEnable == 2">不使用</span>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="form.redisEnable==1">
                <el-form-item label="主机：" prop="redisHost" style="margin-bottom:0;">{{form.redisHost}}</el-form-item>
              </el-col>
              <el-col :span="24" v-if="form.redisEnable==1">
                <el-form-item label="端口：" prop="redisPort" style="margin-bottom:0;">{{form.redisPort}}</el-form-item>
              </el-col>
              <el-col :span="24" v-if="form.redisEnable==1">
                <el-form-item label="连接库：" prop="redisDb" style="margin-bottom:0;">{{form.redisDb}}</el-form-item>
              </el-col>
            </el-tab-pane>
            <el-tab-pane label="其他" name="OTHER" :key="4">
              <el-col :span="24">
                <el-form-item label="Swagger：" prop="swaggerEnable" label-width="100px" style="margin-bottom:0;">
                  <span v-if="form.swaggerEnable == 1">使用</span>
                  <span v-if="form.swaggerEnable == 2">不使用</span>
                </el-form-item>
              </el-col>
            </el-tab-pane>
          </el-tabs>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDetail">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {genProject, saveProject, delProject, getProject, projects, testRedis, testDb} from "@/api/api"
  import '@/store/global'
  export default {
    name: "Project",
    data() {
      return {
        userStatus: userStatus,
        sourceType: sourceType,
        projectItemTab: "PROJECT",
        progress: {},
        genBtnText: "重新生成",
        isGenBtnDisabled: false,
        showSubmitBtn: false,
        isSaveBtnDisabled: false,
        isTestRedisBtnDisabled: false,
        isTestDbBtnDisabled: false,
        // 遮罩层
        loading: true,
        list: [],
        selectedIds: [],
        pageTotal: 0,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        query: {
          name: '',
          pageNo: 0,
          pageSize: 10
        },
        // 表单参数
        form: {},
        genResult: false,
        genDownloadUrl: undefined,
        genResultErr: undefined,
        detail: {
          open: false
        },
        // 表单校验
        rules: {
          code: [{required: true, message: "项目编码不能为空", trigger: "blur"},
            {min: 2, max: 20, message: '项目编码只能输入2~20个字符', trigger: 'blur'}],
          name: [{required: true, message: "项目名称不能为空", trigger: "blur"},
            {min: 1, max: 50, message: '项目名称只能输入1~50个字符', trigger: 'blur'}],
          port: [{required: true, message: "服务端口不能为空", trigger: "blur"}],
          packagePath: [{required: true, message: "项目的包路径不能为空", trigger: "blur"}],

          sourceType: [{required: true, message: "请选择类型", trigger: "blur"}],
          sqlStatement: [{required: true, message: "SQL不能为空", trigger: "blur"}],
          dbHost: [{required: true, message: "主机不能为空", trigger: "blur"}],
          dbUsername: [{required: true, message: "登录用户名不能为空", trigger: "blur"}],
          dbPassword: [{required: true, message: "登录密码不能为空", trigger: "blur"}],
          dbPort: [{required: true, message: "端口不能为空", trigger: "blur"}],
          dbName: [{required: true, message: "连接的数据库名称不能为空", trigger: "blur"}],

          swaggerEnable: [{required: true, message: "请选择是否启用", trigger: "blur"}],
          redisEnable: [{required: true, message: "请选择是否启用", trigger: "blur"}],
          redisHost: [{required: true, message: "主机不能为空", trigger: "blur"}],
          redisPort: [{required: true, message: "端口不能为空", trigger: "blur"}],
          redisDb: [{required: true, message: "连接库不能为空", trigger: "blur"}],
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      openDoenload(row) {
        window.open(row.downloadUrl);
      },
      testDb() {
        this.isTestDbBtnDisabled = true
        testDb(this.form).then(res=>{
          res.data ? this.msgSuccess("连接数据库成功") : this.errorSuccess("连接数据库失败")
          this.isTestDbBtnDisabled = false
        }).catch(() => {
          this.isTestDbBtnDisabled = false
        })
      },
      testRedis() {
        this.isTestRedisBtnDisabled = true
        testRedis(this.form).then(res=>{
          res.data ? this.msgSuccess("连接Redis成功") : this.errorSuccess("连接Redis失败")
          this.isTestRedisBtnDisabled = false
        }).catch(() => {
          this.isTestRedisBtnDisabled = false
        })
      },
      lastStep() {
        this.progress.step--
        this.setProgressPercent()
      },
      nextStep() {
        this.$refs["form"].validate(valid => {
          if (!valid) {
            return
          }
          this.progress.step++
          this.setProgressPercent()
        })
      },
      setProgressPercent() {
        this.progress.percent = this.progress.stepSize * this.progress.step
        if(this.progress.step < 0) {
          this.progress.step = 0
        } else if(this.progress.step >= 6) {
          this.progress.step = 6
          this.progress.percent = 100
        }
        if(this.progress.step == 0) {
          this.title = "设置项目信息"
        } else if(this.progress.step == 1) {
          this.title = "设置数据库信息"
        } else if(this.progress.step == 2) {
          this.title = "设置生成数据来源信息"
        } else if(this.progress.step == 3) {
          this.title = "设置Redis信息"
        } else if(this.progress.step == 4) {
          this.title = "设置其他信息"
          this.showSubmitBtn = true
        } else if(this.progress.step == 5) {
          this.title = "准备生成项目"
          this.showSubmitBtn = true
        } else if(this.progress.step = 6) {
          this.title = "生成结果"
        }
      },
      showDetail(row) {
        this.form = row
        this.detail.open = true
        this.detail.title = "查看【" + row.name+ "】项目配置信息"
      },
      cancelDetail() {
        this.detail.open = false
        this.projectItemTab = "PROJECT"
      },
      getList() {
        this.loading = true;
        projects(this.query).then(response => {
          this.list = response.data.records;
          this.query.pageNo = response.data.current;
          this.pageTotal = response.data.total;
          this.loading = false
        })
      },
      // 取消按钮
      cancel() {
        this.open = false
      },
      /** 搜索按钮操作 */
      handleSearch() {
        this.getList();
      },
      /** 重置按钮操作 */
      resetSearch() {
        this.query = {}
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        this.progress.progressStatus = undefined
        this.progress.percent = 0
        this.open = true
        this.form = row || {
          id: undefined,
          name: '',
          port: 8080,
          dbPort: 3306,
          redisDb: 0,
          redisPort: 6379,
          redisEnable: 1,
          swaggerEnable: 1,
        }
        this.progress = {
          // 每步进度占比。6 * 17 = 102
          percent: 0,
          step: 0,
          stepSize: 17,
          progressStatus: undefined,
        }
        this.setProgressPercent()
      },
      /** 提交按钮 */
      submitForm: function () {
        this.isSaveBtnDisabled = true
        this.$refs["form"].validate(valid => {
          if (!valid) {
            this.isSaveBtnDisabled = false
            return
          }

          let that = this
          saveProject(this.form).then(response => {
            if(1 == response.code) {
              that.msgSuccess("生成项目成功")
              that.genResult = true
              that.genDownloadUrl = response.data
              that.getList()
              that.isSaveBtnDisabled = false
              that.nextStep()
            } else {
              that.genResult = false
            }
          }).catch(res => {
            this.isSaveBtnDisabled = false
            this.genResult = false
            this.genResultErr = res.msg
          });
        });
      },
      /** 删除按钮操作 */
      handleDel(row) {
        let that = this
        this.$confirm('是否确认删除【' + row.name + '】?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          delProject(row.id).then(() => {
            that.getList();
            that.msgSuccess("删除成功");
          })
        })
      },
      // 分页导航
      handlePageChange(val) {
        this.query.pageNo = val
        this.getList(this.query)
      },
      genProject(index, row) {
        this.genBtnText = "生成中"
        this.isGenBtnDisabled = true
        let projectId = row.id
        genProject(projectId).then(res => {
          if(res.code == 1) {
            this.msgSuccess("项目生成成功")
            this.list[index].downloadUrl = res.data
          } else {
            this.errorSuccess("项目生成失败")
          }
          this.genBtnText = "重新生成"
          this.isGenBtnDisabled = false
        }).catch(() => {
          this.genBtnText = "重新生成"
          this.isGenBtnDisabled = false
        })
      },
    }
  };
</script>
